﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleSocket.Samples.ChatServer
{
    class Program
    {
        public static List<ChatClient> ConnectedClients = new List<ChatClient>();

        static void Main(string[] args)
        {
            SimpleSocketServer server = new SimpleSocketServer(5898);
            server.ClientConnected += new ClientConnectedEventHandler(server_ClientConnected);
            server.Listen();

            Console.WriteLine("Server Started. Listing on Port: " + server.Port);
            Console.WriteLine("Press Enter to exit the server.");
            Console.ReadLine();
        }

        static void server_ClientConnected(object server, ClientConnectedEventArgs args)
        {
            ChatClient client = new ChatClient(args.Client, ConnectedClients);
            ConnectedClients.Add(client);
            client.Client.Disconnected += new ConnectionStateEventHandler(Client_Disconnected);

            Console.WriteLine("Client Connected: {0}", args.Client.RemoteEndPoint);
        }

        static void Client_Disconnected(object sender, EventArgs Args)
        {
            SimpleSocketClient client = (SimpleSocketClient)sender;
            Console.WriteLine("Client Disconnected: {0}", client.RemoteEndPoint);
            ChatClient chatClient = ConnectedClients.Where(c => c.Client == client).Single();
            ConnectedClients.Remove(chatClient);
            chatClient.Dispose();
            GC.Collect();
        }
    }
}
